const fs = require('fs');
const path = require('path');
const crc32 = require('crc32');
const iconv = require('iconv-lite');
const cdn = require('../cdn');

const soft_dir = 'D:/soft';
const soft_file = path.join(__dirname, 'soft.json');
const cmd_file = path.join(__dirname, 'soft.cmd');

(async() => {
    const dir = mkdir(soft_dir);
    const softs = loadSoft();
    const files = fs.readdirSync(dir);
    let success = 0, failed = 0;
    for (let i = 0; i < files.length; i++) {
        const f = files[i];
        const ext = path.extname(f);
        if (['.7z', '.zip', '.exe'].indexOf(ext) !== -1) {
            const file = path.join(dir, f);
            const bytes = fs.readFileSync(file);
            if (bytes.length === 0) {
                fs.unlinkSync(file);
                continue;
            }
            const crc32 = fileCRC32(bytes);
            if (softs[f] && softs[f].crc32 === crc32) {
                continue; // 哈希相同跳过
            }
            console.log(`CDN上传 ${f} ...`);
            const ret = await cdn(file);
            if (ret) {
                success++;
                if (!softs[f]) {
                    softs[f] = {};
                }
                const ss = fs.statSync(file);
                softs[f].atime = time(ss.atime);
                softs[f].ctime = time(ss.ctime);
                softs[f].mtime = time(ss.mtime);
                softs[f].crc32 = crc32;
                softs[f].size = fileSize(bytes.length);
            } else {
                failed++;
            }
        }
    }
    const total = Object.keys(softs).length;
    console.log(`已上传${success}个，上传失败${failed}个，当前共${total}个软件包。`);
    fs.writeFileSync(soft_file, JSON.stringify(softs, null, 2), 'utf-8');
    toCMD(softs);
})().catch(err => console.log(err));


function loadSoft() {
    try {
        if (fs.existsSync(soft_file)) {
            const text = fs.readFileSync(soft_file, 'utf-8');
            return JSON.parse(text);
        }
    } catch (e) {}
    return {};
}

function fileCRC32(bytes) {
    return crc32(bytes).toUpperCase()
}

function fileSize(length, decimals = 2) {
    if (length === 0) return '0 Bytes';
    const k = 1024;
    const dm = decimals < 0 ? 0 : decimals;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
    const i = Math.floor(Math.log(length) / Math.log(k));
    return parseFloat((length / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i];
}

function toCMD(softs) {
    const cmd = ['@echo off'];
    cmd.push(`cd "${__dirname}"`);
    const keys = Object.keys(softs);
    for(let i = 0; i < keys.length; i++) {
        cmd.push(`echo ${i + 1}. ${keys[i]} \t ${softs[keys[i]].size}`);
    }
    cmd.push(`:Step0`);
    cmd.push(`set choice=''`);
    cmd.push(`set /p choice=输入序号: `);
    for(let i = 0; i < keys.length; i++) {
        cmd.push(`if %choice%==${i + 1} goto Step${i + 1}`);
    }
    cmd.push(`goto Step0`);
    for(let i = 0; i < keys.length; i++) {
        cmd.push(`:Step${i + 1}`);
        cmd.push(`echo 准备下载 ${keys[i]} ...`);
        // cmd.push(`node fetch.js ${keys[i]}`);
        cmd.push(`wget -c -O "D:\\soft\\${keys[i]}" "http://upload.liuzy88.com/${keys[i]}"`);
        cmd.push(`goto Step0`);
    }
    cmd.push(`pause`);
    const gbk = iconv.encode(cmd.join('\r\n'), 'gbk');
    fs.writeFileSync(cmd_file, gbk);
}

function mkdir(dirpath) {
    if (!fs.existsSync(dirpath)) {
        fs.mkdirSync(dirpath);
    }
    return dirpath;
}

function time(d) {
    return [d.getFullYear(), '-',
        ('0' + (d.getMonth() + 1)).slice(-2), '-',
        ('0' + d.getDate()).slice(-2), ' ',
        ('0' + d.getHours()).slice(-2), ':',
        ('0' + d.getMinutes()).slice(-2), ':',
        ('0' + d.getSeconds()).slice(-2)
    ].join('')
}